//
//  AppleSignManager.m
//  WXReader
//
//  Created by Chair on 2020/1/27.
//  Copyright © 2020 Andrew. All rights reserved.
//

#import "TL_AppleSignManager.h"

#import <AuthenticationServices/AuthenticationServices.h>
#import "AppDelegate.h"

@interface TL_AppleSignManager ()<ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding>

@end

@implementation TL_AppleSignManager

SINGLETON_IMPLEMENTATION(TL_AppleSignManager)

- (void)tunedUpAppleSignWithState:(TL_appleSignState)state {
    ASAuthorizationAppleIDProvider *provider = [[ASAuthorizationAppleIDProvider alloc] init];
    ASAuthorizationAppleIDRequest *request = [provider createRequest];
    request.requestedScopes = @[ASAuthorizationScopeFullName, ASAuthorizationScopeEmail];

    ASAuthorizationController *vc = [[ASAuthorizationController alloc] initWithAuthorizationRequests:@[request]];
    vc.delegate = self;
    vc.presentationContextProvider = self;
    [vc performRequests];
}

#pragma mark - ASAuthorizationControllerPresentationContextProviding
- (ASPresentationAnchor)presentationAnchorForAuthorizationController:(ASAuthorizationController *)controller  API_AVAILABLE(ios(13.0)) {
    AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    return app.window;
}

#pragma mark - ASAuthorizationControllerDelegate
- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithAuthorization:(ASAuthorization *)authorization API_AVAILABLE(ios(13.0)) {
    if ([authorization.credential isKindOfClass:[ASAuthorizationAppleIDCredential class]])       {
        /*
         ASAuthorizationAppleIDCredential *credential = authorization.credential;
        NSString *state = credential.state;
        NSString *userID = credential.user;
        NSPersonNameComponents *fullName = credential.fullName;
        NSString *email = credential.email;
        NSString *authorizationCode = [[NSString alloc] initWithData:credential.authorizationCode encoding:NSUTF8StringEncoding]; // refresh token
        NSString *identityToken = [[NSString alloc] initWithData:credential.identityToken encoding:NSUTF8StringEncoding]; // access token
        ASUserDetectionStatus realUserStatus = credential.realUserStatus;
         */
        
        // 请求游客登录
//        [self requestTouristsLogin];
    }
}

/// 请求游客登录
- (void)requestTouristsLogin {
    MK_WEAK_SELF

    [APIManager sendPostRequest:[APIURLManager Tourists_Login] parameters:@{@"udid":[TL_UtilsHelper getUDID]} model:TL_UserInfoModel.class success:^(BOOL success, TL_UserInfoModel*  _Nullable responseData, APIResponse * _Nonnull requestModel) {
        [TL_TopAlertManager hiddenAlert];
        if (success) {
            if (responseData.is_new) {
//                [TL_AnalyticsManager logEvent:@"registration" params:@{}];
            }
            [weakSelf appleSignResponseSuccess:responseData];
        } else {
            [weakSelf appleSignResponseFail:requestModel.msg];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [TL_TopAlertManager hiddenAlert];
        [weakSelf appleSignResponseFail:error.localizedFailureReason ?: WXLocalizedString(@"登录失败")];
    }];
    
    
}

- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithError:(NSError *)error API_AVAILABLE(ios(13.0)) {
    NSString *errorMsg = nil;
    switch (error.code) {
        case ASAuthorizationErrorCanceled:
            errorMsg = WXLocalizedString(@"您已取消授权");
            break;
        case ASAuthorizationErrorFailed:
            errorMsg = WXLocalizedString(@"授权请求失败");
            break;
        case ASAuthorizationErrorInvalidResponse:
            errorMsg = WXLocalizedString(@"授权请求响应无效");
            break;
        case ASAuthorizationErrorNotHandled:
            errorMsg = WXLocalizedString(@"未能处理授权请求");
            break;
        case ASAuthorizationErrorUnknown:
            errorMsg = WXLocalizedString(@"授权请求失败原因未知");
            break;
    }
    [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeError alertTitle:errorMsg];
}

- (void)appleSignResponseSuccess:(TL_UserInfoModel *)userData {
    !self.appleLoginSuccess ?: self.appleLoginSuccess(userData, self);
    if (self.delegate && [self.delegate respondsToSelector:@selector(appleSignResponseSuccess:)]) {
        [self.delegate appleSignResponseSuccess:userData];
    }
}

- (void)appleSignResponseFail:(NSString *)error {
    !self.appleLoginError ?: self.appleLoginError(error, self);
    if (self.delegate && [self.delegate respondsToSelector:@selector(appleSignResponseFail:)]) {
        [self.delegate appleSignResponseFail:error ?: @""];
    }
}

@end
